#!/usr/bin/python
#coding=utf-8

from app.common import import_obj
from app.common import render 

class Router(object):
    """路由类，根据路径信息调用相应的
    处理对象进行处理。
    """
    
    def __init__(self):
        self.path_mapper = {}

    def __call__(self, path, handler_cls):  
        self.path_mapper[path] =  handler_cls

    def route(self, req, resp):
        handler_cls = self.path_mapper.get(req.path_info)  
        if not handler_cls:
            return self.missed(req, resp)
        handler = import_obj(handler_cls)
        method = req.method
        if method == 'GET':
            return handler.get(req, resp)
        elif method == 'POST':
            return handler.post(req, resp)
        elif method == 'PUT':
            return handler.put(req, resp)
        elif method == 'HEAD':
            return handler.head(req, resp)
        else:
            return handler.error(req, resp, '501 Not Implemented')

    def missed(self, req, resp):
        resp.status = '404 Not Found'
        body = render('notfound.html')
        return resp.respond(body)

    
